/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved. 
 */
package com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.dto.AppraisalReportRequest;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.dto.AppraisalThing;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.dto.CaseDocumentAppraisalYjgzsDto;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentAppraisalYjgzsMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentAppraisalYjgzs;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.ICaseDocumentAppraisalYjgzsService;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.vo.AppraisalReportInfoVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.MapUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 鉴定意见告知书 case_document_appraisal_yjgzs 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年04月25日
 */
@Service
public class CaseDocumentAppraisalYjgzsServiceImpl extends MyBatisServiceSupport implements ICaseDocumentAppraisalYjgzsService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseDocumentAppraisalYjgzsServiceImpl.class);

    @Autowired
    private CaseDocumentAppraisalYjgzsMapper caseDocumentAppraisalYjgzsMapper;
    @Autowired
    private CaseMainInfoMapper caseMainInfoMapper;
    @Value("${evidence.url}")
    private String url;
    @Value("${evidence.api.appraisalReport}")
    private String appraisalReport;
    @Autowired
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Autowired
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Autowired
    private ICasePartiesRecordService casePartiesRecordService;
    @Autowired
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    /**
     * 获取状态为已完成且未生成过鉴定意见告知书的鉴定报告
     * @author liyafeng
     * @date 2022/4/25
      * @param request
     * @return {@link Result< AppraisalReportInfoVo>}
     */
    @Override
    public List<AppraisalReportInfoVo> getAppraisalReportInfo(AppraisalReportRequest request) {
        String caseId = request.getCaseId();
        /*CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(request.getCaseId());
        List<AppraisalReportInfoVo> appraisalReportInfoVos=new ArrayList<>();*/

       /* try {
            long timestamp=System.currentTimeMillis();
            //调用证据库接口获取鉴定报告相关数据
            JSONObject param = new JSONObject();
            param.put("caseNo", caseMainInfo.getCaseNumber());
            param.put("appKey", "c37c14e6a33711ecb6fb0050568f7529");
            //todo
            //param.put("sign", );
            param.put("timestamp", String.valueOf(timestamp));
            Map<String, String> headers = HeaderUtil.headerInfo();
            String response = HttpUtil.createPost(url.concat(appraisalReport)).body(param.toJSONString()).headerMap(headers,true).execute().body();
            JSONObject info = JSONObject.parseObject(response);
            int code=info.getInteger("code");
            if(200==code){
                JSONArray array = info.getJSONArray("data");
                for (int i = 0; i < array.size(); i++) {
                    AppraisalReportInfoVo appraisalReportInfoVo= JSON.parseObject(array.getJSONObject(i).toJSONString(), AppraisalReportInfoVo.class);
                    appraisalReportInfoVo.setCaseId(request.getCaseId());
                    appraisalReportInfoVo.setDocumentCatalogCode(request.getDocumentCatalogCode());
                    allAppraisalReportInfoVos.add(appraisalReportInfoVo);
                }
            }else{
                throw new BusinessException("获取鉴定报告失败！");
            }
        }catch (Exception e){
            throw new BusinessException("获取鉴定报告异常！");
        }
        //判断是否已经生成鉴定意见告知书
        List<AppraisalReportInfoVo> appraisalReportInfoVos=new ArrayList<>();
        for (AppraisalReportInfoVo appraisalReportInfoVo:allAppraisalReportInfoVos) {
            Example example=new Example(CaseDocumentAppraisalYjgzs.class);
            example.createCriteria().andEqualTo("caseId","").andEqualTo("documentCatalogCode","").andEqualTo("courierNumber","").andEqualTo("reportTitle","")
            .andEqualTo("isDeleted","0").andEqualTo("isGenFile","1");
            List<CaseDocumentAppraisalYjgzs> caseDocumentAppraisalYjgzs=caseDocumentAppraisalYjgzsMapper.selectByExample(example);
            if(caseDocumentAppraisalYjgzs.size()>0){
                continue;
            }
            appraisalReportInfoVos.add(appraisalReportInfoVo);
        }*/
        //查询当事人
        List<CasePartiesRecordVo> casePartiesRecordList=casePartiesRecordService.getCasePartiesInfo(caseId);
        //当事人
        List<String> partiesList=new ArrayList<>();
        //承办人员list
        List<String> handlePersonList=new ArrayList<>();
        String handleOrgTel="";
        for (CasePartiesRecordVo casePartiesRecord:casePartiesRecordList) {
            partiesList.add(casePartiesRecord.getPartyName());
        }
        //查询承办人
        Example handleExample=new Example(CaseHandlePersonRecord.class);
        handleExample.createCriteria().andEqualTo("caseId",request.getCaseId()).andEqualTo("status", Constant.STRING_1);
        handleExample.setOrderByClause("handle_person_type asc");
        List<CaseHandlePersonRecord> caseHandlePersonRecordList=caseHandlePersonRecordMapper.selectByExample(handleExample);
        for (CaseHandlePersonRecord caseHandlePersonRecord:caseHandlePersonRecordList) {
            handlePersonList.add(caseHandlePersonRecord.getHandlePersonName());
            handleOrgTel=caseHandlePersonRecord.getHandleOrgTel();
        }
        //查询鉴定报告
        Example example=new Example(CaseDocumentAppraisalYjgzs.class);
        example.createCriteria().andEqualTo("caseId",request.getCaseId())
                .andEqualTo("isDeleted","0").andEqualTo("isGenFile","0");
        List<CaseDocumentAppraisalYjgzs> caseDocumentAppraisalYjgzsList=caseDocumentAppraisalYjgzsMapper.selectByExample(example);
        List<AppraisalReportInfoVo> appraisalReportInfoVos=new ArrayList<>();
        for (CaseDocumentAppraisalYjgzs caseDocumentAppraisalYjgzs:caseDocumentAppraisalYjgzsList) {
            AppraisalReportInfoVo appraisalReportInfoVo=new AppraisalReportInfoVo();
            appraisalReportInfoVo.setDocumentCatalogCode(request.getDocumentCatalogCode());
            appraisalReportInfoVo.setCaseId(request.getCaseId());
            List<AppraisalThing> appraisalThings=JSON.parseArray(caseDocumentAppraisalYjgzs.getAppraisalThings(),AppraisalThing.class);
            appraisalReportInfoVo.setAppraisalThings(appraisalThings);
            appraisalReportInfoVo.setClientOrgcode(caseDocumentAppraisalYjgzs.getClientOrgcode());
            appraisalReportInfoVo.setCourierNumber(caseDocumentAppraisalYjgzs.getCourierNumber());
            appraisalReportInfoVo.setClientOrgname(caseDocumentAppraisalYjgzs.getClientOrgname());
            appraisalReportInfoVo.setReportTitle(caseDocumentAppraisalYjgzs.getReportTitle());
            //url转base64
            String base64=doGetBase64ByPath(caseDocumentAppraisalYjgzs.getReportUrl());
            appraisalReportInfoVo.setReportUrl(base64);
            appraisalReportInfoVo.setHandleOrgTel(handleOrgTel);
            appraisalReportInfoVo.setId(caseDocumentAppraisalYjgzs.getId());
            appraisalReportInfoVo.setHandlePersonList(handlePersonList);
            //先默认写死
            appraisalReportInfoVo.setObjectionDays("3");
            appraisalReportInfoVo.setPartiesList(partiesList);
            appraisalReportInfoVo.setDocumentId(caseDocumentAppraisalYjgzs.getDocumentId());
            appraisalReportInfoVos.add(appraisalReportInfoVo);
        }
        return appraisalReportInfoVos;
    }
    /**
     * 根据地址获取base64
     * @author liyafeng
     * @date 2022/4/28
      * @param path
     * @return {@link String}
     */
    private String doGetBase64ByPath(String path){
        String base64="";
        HttpURLConnection conn = null;
        InputStream inputStream=null;
        ByteArrayOutputStream output=null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(1000);
            inputStream=conn.getInputStream();
            //Base64.encodeBase64String(inputStream);
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            base64= Base64.encodeBase64String(output.toByteArray());
        }catch (Exception e){
            throw new BusinessException("获取文件base64失败");
        }finally {
            try {
                conn.disconnect();
                inputStream.close();
                output.close();
            }catch (Exception e){
                e.printStackTrace();
            }


        }
        return base64;
    }
    /**
     *  保存鉴定报告数据并生成鉴定意见告知书
     * @author liyafeng
     * @date 2022/4/25
      * @param caseDocumentAppraisalYjgzsDto
     * @return {@link Result< String>}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveAppraisalReportInfo(CaseDocumentAppraisalYjgzsDto caseDocumentAppraisalYjgzsDto) {
        CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(caseDocumentAppraisalYjgzsDto.getCaseId());
        int num=0;
        //生成鉴定意见告知书
        StageDocCommonOperateSaveDto operateSaveDto=new StageDocCommonOperateSaveDto();
        operateSaveDto.setCaseId(caseDocumentAppraisalYjgzsDto.getCaseId());
        operateSaveDto.setDocumentCatalogCode(caseDocumentAppraisalYjgzsDto.getDocumentCatalogCode());
        operateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);
        operateSaveDto.setIsMultipleDoc(Constant.STRING_1);
        operateSaveDto.setBelongDocumentId(caseDocumentAppraisalYjgzsDto.getDocumentId());
        HashMap<String,Object> dataMap=JSONObject.parseObject(JSONObject.toJSONString(caseDocumentAppraisalYjgzsDto), HashMap.class);
        List<AppraisalThing> list=JSON.parseArray(caseDocumentAppraisalYjgzsDto.getAppraisalThings(),AppraisalThing.class);
        dataMap.put("appraisalThings",list);
        dataMap.put("orgName",caseMainInfo.getCaseOrgName());
        operateSaveDto.setDataMap(dataMap);
        Map<String,Object> docMap=stageDocCommonOperateService.saveDocInfo(operateSaveDto);
        String status= MapUtils.getString(docMap,"success","");
        String documentId=MapUtils.getString(docMap,"documentId","");
        if(!"true".equals(status)){
            num=0;
        }else{
            CaseDocumentAppraisalYjgzs updateCaseDocumentAppraisalYjgzs=new CaseDocumentAppraisalYjgzs();
            updateCaseDocumentAppraisalYjgzs.setId(caseDocumentAppraisalYjgzsDto.getId());
            updateCaseDocumentAppraisalYjgzs.setIsDeleted(Constant.STRING_0);
            updateCaseDocumentAppraisalYjgzs.setIsGenFile(Constant.STRING_1);
            updateCaseDocumentAppraisalYjgzs.setDocumentId(documentId);
            num=caseDocumentAppraisalYjgzsMapper.updateByPrimaryKeySelective(updateCaseDocumentAppraisalYjgzs);
        }
        return num;
    }
    /**
     * 根据用户获取未生成鉴定意见告知书列表
     * @author liyafeng
     * @date 2022/5/5
     * @param userId
     * @return {@link List< AppraisalReportInfoVo>}
     */
    @Override
    public List<AppraisalReportInfoVo> getAppraisalReportInfoByUserId(String userId) {
        //根据主办人员查询案件id
        Example handleExample=new Example(CaseHandlePersonRecord.class);
        handleExample.createCriteria().andEqualTo("handlePersonId",userId).andEqualTo("status", Constant.STRING_1);
        List<CaseHandlePersonRecord>  caseHandlePersonRecordList=caseHandlePersonRecordMapper.selectByExample(handleExample);
        List<AppraisalReportInfoVo> appraisalReportInfoVos=new ArrayList<>();
        for (CaseHandlePersonRecord caseHandlePersonRecord:caseHandlePersonRecordList) {
            //查询鉴定报告
            Example example=new Example(CaseDocumentAppraisalYjgzs.class);
            example.createCriteria().andEqualTo("caseId",caseHandlePersonRecord.getCaseId())
                    .andEqualTo("isDeleted","0").andEqualTo("isGenFile","0");
            List<CaseDocumentAppraisalYjgzs> caseDocumentAppraisalYjgzsList=caseDocumentAppraisalYjgzsMapper.selectByExample(example);
            for (CaseDocumentAppraisalYjgzs caseDocumentAppraisalYjgzs:caseDocumentAppraisalYjgzsList) {
                AppraisalReportInfoVo appraisalReportInfoVo=new AppraisalReportInfoVo();
                appraisalReportInfoVo.setDocumentCatalogCode("");
                appraisalReportInfoVo.setCaseId(caseHandlePersonRecord.getCaseId());
                List<AppraisalThing> appraisalThings=JSON.parseArray(caseDocumentAppraisalYjgzs.getAppraisalThings(),AppraisalThing.class);
                appraisalReportInfoVo.setAppraisalThings(appraisalThings);
                appraisalReportInfoVo.setClientOrgcode(caseDocumentAppraisalYjgzs.getClientOrgcode());
                appraisalReportInfoVo.setCourierNumber(caseDocumentAppraisalYjgzs.getCourierNumber());
                appraisalReportInfoVo.setClientOrgname(caseDocumentAppraisalYjgzs.getClientOrgname());
                appraisalReportInfoVo.setReportTitle(caseDocumentAppraisalYjgzs.getReportTitle());
                //url转base64
                String base64=doGetBase64ByPath(caseDocumentAppraisalYjgzs.getReportUrl());
                appraisalReportInfoVo.setReportUrl(base64);
                appraisalReportInfoVo.setId(caseDocumentAppraisalYjgzs.getId());
                //先默认写死
                appraisalReportInfoVo.setObjectionDays("3");
                appraisalReportInfoVo.setDocumentId(caseDocumentAppraisalYjgzs.getDocumentId());
                appraisalReportInfoVos.add(appraisalReportInfoVo);
            }
        }
        return appraisalReportInfoVos;
    }
}